<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.web.rest;

<%_ if (searchEngineElasticsearch) { _%>
import <%= packageName %>.repository.search.UserSearchRepository;
<%_ } else if (searchEngineCouchbase) { _%>
import <%= packageName %>.repository.UserRepository;
import <%= packageName %>.domain.User;
  <%_ if (!reactive) { _%>
import java.util.stream.StreamSupport;
  <%_ } _%>
<%_ } _%>
<%_ if (!authenticationTypeOauth2) { _%>
import org.springframework.data.domain.Sort;
  <%_ if (reactive) { _%>
import java.util.Collections;
  <%_ } _%>
<%_ } _%>
import <%= packageName %>.service.UserService;
import <%= packageName %>.service.dto.<%= user.dtoClass %>;

<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
import tech.jhipster.web.util.PaginationUtil;
<%_ } _%>

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
  <%_ if (reactive) { _%>
import org.springframework.data.domain.PageImpl;
  <%_ } else { _%>
import org.springframework.data.domain.Page;
  <%_ } _%>
import org.springframework.data.domain.Pageable;
  <%_ if (!reactive) { _%>
import org.springframework.http.HttpHeaders;
  <%_ } _%>
<%_ } _%>
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
<%_ if (reactive) { _%>
import org.springframework.http.server.reactive.ServerHttpRequest;
<%_ } _%>
import org.springframework.web.bind.annotation.*;
<%_ if (reactive) { _%>
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.util.ForwardedHeaderUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
<%_ } else {_%>
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
<%_ } _%>

<%_ if (reactive) { _%>
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
<%_ } else { _%>
import java.util.*;
<%_ } _%>
<%_ if (searchEngineElasticsearch && !reactive) { _%>
import java.util.stream.StreamSupport;
<%_ } _%>

@RestController
@RequestMapping("/api")
public class PublicUserResource {
<%_ if (!authenticationTypeOauth2) { _%>
    private static final List<String> ALLOWED_ORDERED_PROPERTIES = Collections.unmodifiableList(Arrays.asList("id", "login", "firstName", "lastName", "email", "activated", "langKey"));
<%_ } _%>

    private static final Logger LOG = LoggerFactory.getLogger(PublicUserResource.class);

    private final UserService userService;
<%_ if (searchEngineElasticsearch) { _%>
    private final UserSearchRepository userSearchRepository;
<%_ } else if (searchEngineCouchbase) { _%>
    private final UserRepository userRepository;
<%_ } _%>

    public PublicUserResource(
<%_ if (searchEngineElasticsearch) { -%>
        UserSearchRepository userSearchRepository,
<%_ } else if (searchEngineCouchbase) { -%>
        UserRepository userRepository,
<%_ } -%>
        UserService userService
    ) {
        this.userService = userService;
<%_ if (searchEngineElasticsearch) { _%>
        this.userSearchRepository = userSearchRepository;
<%_ } else if (searchEngineAny) { _%>
        this.userRepository = userRepository;
<%_ } _%>
    }

    /**
     * {@code GET /users} : get all users with only public information - calling this method is allowed for anyone.
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
     *
  <%_ if (reactive) { _%>
     * @param request a {@link ServerHttpRequest} request.
  <%_ } _%>
     * @param pageable the pagination information.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
<%_ } _%>
     */
    @GetMapping("/users")
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
  <%_ if (reactive) { _%>
    public Mono<ResponseEntity<Flux<<%= user.dtoClass %>>>> getAllPublicUsers(ServerHttpRequest request, @org.springdoc.core.annotations.ParameterObject Pageable pageable) {
        LOG.debug("REST request to get all public User names");
    <%_ if (!authenticationTypeOauth2) { _%>
        if (!onlyContainsAllowedProperties(pageable)) {
            return Mono.just(ResponseEntity.badRequest().build());
        }
    <%_ } _%>

        return userService.countManagedUsers()
            .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total))
            .map(page -> PaginationUtil.generatePaginationHttpHeaders(ForwardedHeaderUtils.adaptFromForwardedHeaders(request.getURI(), request.getHeaders()), page))
            .map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllPublicUsers(pageable)));
    }
  <%_ } else { _%>
    public ResponseEntity<List<<%= user.dtoClass %>>> getAllPublicUsers(@org.springdoc.core.annotations.ParameterObject Pageable pageable) {
        LOG.debug("REST request to get all public User names");
    <%_ if (!authenticationTypeOauth2) { _%>
        if (!onlyContainsAllowedProperties(pageable)) {
            return ResponseEntity.badRequest().build();
        }
    <%_ } _%>

        final Page<<%= user.dtoClass %>> page = userService.getAllPublicUsers(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }
  <%_ } _%>
  <%_ if (!authenticationTypeOauth2) { _%>
    private boolean onlyContainsAllowedProperties(Pageable pageable) {
        return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains);
    }
  <%_ } _%>

<%_ } else { /* Cassandra */ _%>
    public <% if (reactive) { %>Flux<% } else { %>List<% } %><<%= user.dtoClass %>> getAllPublicUsers() {
        return userService.getAllPublicUsers();
    }

<%_ } _%>

<%_ if (searchEngineAny) { _%>

    /**
     * {@code SEARCH /users/_search/:query} : search for the User corresponding to the query.
     *
     * @param query the query to search.
     * @return the result of the search.
     */
    @GetMapping("/users/_search/{query}")
    public <% if(reactive) { %>Mono<<% } %>List<<%= user.dtoClass %>><% if(reactive) { %>><% } %> search(@PathVariable("query") String query) {
  <%_ if (searchEngineElasticsearch) { _%>
    <%_ if (reactive) { _%>
        return userSearchRepository.search(query).map(<%= user.dtoClass %>::new).collectList();
    <%_ } else { _%>
        return StreamSupport
            .stream(userSearchRepository.search(query).spliterator(), false)
            .map(<%= user.dtoClass %>::new)
            .toList();
    <%_ } _%>
  <%_ } else { _%>
     <%_ if (reactive) { _%>
        return userRepository.search(query).map(<%= user.dtoClass %>::new).collectList();
     <%_ } else { _%>
        return StreamSupport
            .stream(userRepository.search(query).spliterator(), false)
            .map(<%= user.dtoClass %>::new)
            .toList();
     <%_ } _%>
  <%_ } _%>
    }
<%_ } _%>

}
